package org.budo.netty.servlet.server.handler;

import java.io.IOException;
import java.util.List;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.budo.netty.servlet.server.BudoServletServer;
import org.budo.netty.servlet.server.filter.chain.BudoFilterChain;
import org.budo.netty.servlet.server.handler.servlet.BudoServletRequest;
import org.budo.netty.servlet.server.handler.servlet.ServletResolved;

import lombok.Setter;

import lombok.Getter;

/**
 * @author li
 */
@Getter
@Setter
public class DefaultBudoServletHandler implements BudoServletHandler {
    private BudoServletServer budoServletServer;

    public DefaultBudoServletHandler(BudoServletServer budoServletServer) {
        this.setBudoServletServer(budoServletServer);
    }

    @Override
    public void handlerRequest(HttpServletRequest request, HttpServletResponse response, DispatcherType dispatcherType) throws ServletException, IOException {
        this.getBudoServletServer().getEventBus().requestInitialized(request);

        this.doHandlerRequest(request, response, dispatcherType);

        this.getBudoServletServer().getEventBus().requestDestroyed(request);
    }

    private void doHandlerRequest(HttpServletRequest request, HttpServletResponse response, DispatcherType dispatcherType) throws IOException, ServletException {
        ServletResolved servletResolved = this.getBudoServletServer().resolveServlet(request);

        // 放入 servlet 信息
        ((BudoServletRequest) request).setServletResolved(servletResolved);

        List<Filter> filters = this.getBudoServletServer().resolveFilter(request, dispatcherType);
        BudoFilterChain filterChain = new BudoFilterChain(filters, servletResolved.getServletInstance());

        filterChain.doFilter(request, response); // do chain
    }
}